﻿using System;
using System.Windows.Forms;
using Business.Forms;

namespace Business.Controls
{
    public class CommandUpdate : CommandBase
    {
        public CommandUpdate()
        {
            InitializeComponent();
        }
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // CommandInsert
            // 
            Atalho = Keys.F8;
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CommandInsert_KeyDown);
            this.ResumeLayout(false);
            this.Text = "Alterar";
        }

        private void CommandInsert_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyData == Atalho)
            {
                UpdateObject();
            }
        }

        private void UpdateObject()
        {
            BeforeOperation();
            try
            {
                Form.Form.DialogResult = DialogResult.None;
                Form.FormState = FormState.Updating;
                Form.Form.Activated += Form_Activated;
                Form.Update(Form.CurrentObject);
            }
            catch (Exception ex)
            {
                ExibeErro("Erro ao atualizar item.\n" + ex.Message);
            }
            AfterOperation();
        }

        void Form_Activated(object sender, EventArgs e)
        {
            AfterOperation();
        }

        public override void Actived()
        {
            if (Form == null)
            {
                return;
            }
            var perm = Seguranca.SegurancaUtils.GetPermissaoForm(Form.Form.Name);
            if (Form != null && Form.Permissao != null && perm.PermissaoUpdate)
            {
                Enabled = true;
            }
            else
            {
                Enabled = false;
            }
        }
    }
}
